package models

import (
	"encoding/json"
	"fmt"
	"net/url"
	"strconv"
	"strings"
	"time"
)

type CollectionData struct {
	CollectionID string `json:"collection_id"`
	DatasetID    string `json:"dataset_id"`
	Value        string `json:"value"`
}

type Gold struct {
	ID             int             `gorm:"primaryKey;autoIncrement;comment:编号"`
	Enable         int             `gorm:"comment:启用"`
	ServerID       int             `gorm:"column:server_id;comment:服务器"`
	ServiceID      string          `gorm:"column:service_id;default:lgc_service_1;comment:服务"`
	Sku            string          `gorm:"comment:来源"`
	Game           string          `gorm:"comment:游戏"`
	Title          string          `gorm:"comment:名称"`
	Collect        string          `gorm:"comment:集合"`
	Dataset        string          `gorm:"comment:数据"`
	Price          float64         `gorm:"type:decimal(12,8);comment:价格"`
	Currency       string          `gorm:"default:USD;comment:货币"`
	OfferAttribute json.RawMessage `gorm:"column:offer_attribute;type:json"`
	CreatedAt      time.Time       `gorm:"column:created_at"`
	UpdatedAt      time.Time       `gorm:"column:updated_at"`
	CreateTime     int64           `gorm:"column:create_time"`
	UpdateTime     int64           `gorm:"column:update_time"`
}

func (s *Gold) TableName() string {
	return "yf_g2g_gold"
}

func (s *Gold) Uri() string {
	search := s.QueryUrl()
	values := url.Values{}
	for k, v := range search {
		switch vs := v.(type) {
		case string:
			values.Set(k, vs)
		case int:
			values.Set(k, strconv.Itoa(vs))
		case bool:
			values.Set(k, strconv.FormatBool(vs))
		default:
			fmt.Printf("unexpected type %T for key %s\n", v, k)
		}
	}
	return values.Encode()
}

func (s *Gold) QueryUrl() map[string]interface{} {
	search := make(map[string]interface{})
	search["service_id"] = s.ServiceID
	search["brand_id"] = s.Sku
	search["offer_title"] = s.Title
	search["group"] = "1"
	search["sort"] = "recommended"
	search["load_type"] = "full"
	search["offer_sorting"] = "recommended"
	search["offer_online_status"] = 0
	search["fa"] = s.GetFaString()
	return search
}

func (s *Gold) GetFaString() string {
	collects := make([]CollectionData, 0)
	json.Unmarshal(s.OfferAttribute, &collects)
	uri := ""
	for _, item := range collects {
		uri = uri + "|" + item.CollectionID + ":" + item.DatasetID
	}
	return strings.Trim(uri, "|")
}
